package com.atom.module.draw.activities

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.webkit.MimeTypeMap
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.print.PrintHelper
import com.atom.module.draw.R
import com.atom.module.draw.dialogs.SaveImageDialog
import com.atom.module.draw.extensions.config
import com.atom.module.draw.helpers.EyeDropper
import com.atom.module.draw.helpers.JPG
import com.atom.module.draw.helpers.PNG
import com.atom.module.draw.helpers.SVG
import com.atom.module.draw.interfaces.CanvasListener
import com.atom.module.draw.models.Svg
import com.atom.module.draw.views.MyCanvas
import com.atom.module.permissions.AutoPermissions
import com.atom.module.permissions.AutoPermissionsCallback
import com.simplemobiletools.commons.dialogs.ColorPickerDialog
import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.SAVE_DISCARD_PROMPT_INTERVAL
import com.simplemobiletools.commons.helpers.isQPlus
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.MySeekBar
import java.io.*
import java.util.HashMap

class DrawActivity : AppCompatActivity(), CanvasListener {
    private val PICK_IMAGE_INTENT = 1
    private val SAVE_IMAGE_INTENT = 2

    private val FOLDER_NAME = "images"
    private val FILE_NAME = "simple-draw.png"
    private val BITMAP_PATH = "bitmap_path"
    private val URI_TO_LOAD = "uri_to_load"

    private lateinit var eyeDropper: EyeDropper

    private var defaultPath = ""
    private var defaultFilename = ""

    private var defaultExtension = PNG
    private var intentUri: Uri? = null
    private var uriToLoad: Uri? = null
    private var color = 0
    private var brushSize = 0f
    private var savedPathsHash = 0L
    private var lastSavePromptTS = 0L
    private var isEraserOn = false
    private var isEyeDropperOn = false
    private var isImageCaptureIntent = false
    private var isEditIntent = false
    private var lastBitmapPath = ""


    val views: MutableMap<Int, View> = HashMap()

    fun <T : View> view(@IdRes id: Int, pickView: (T) -> Unit) {
        var view = views[id]
        if (view == null) {
            view = this.findViewById(id)
            views[id] = view
        }
        if (view == null) return
        pickView.invoke(view as T)
    }

    fun <T : View, R> viewReturn(@IdRes id: Int, pickView: (T) -> R): R {
        var view = views[id]
        if (view == null) {
            view = this.findViewById(id)
            views[id] = view
        }
        if (view == null) throw RuntimeException("view == null")
        return pickView.invoke(view as T)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_draw)
        view(R.id.my_canvas) { t: MyCanvas ->
            eyeDropper = EyeDropper(t) { selectedColor ->
                setColor(selectedColor)
            }
            t.mListener = this
        }
        view(R.id.stroke_width_bar) { t: MySeekBar ->
            t.setOnSeekBarChangeListener(onStrokeWidthBarChangeListener)
        }
        setBackgroundColor(config.canvasBackgroundColor)
        setColor(config.brushColor)
        defaultPath = config.lastSaveFolder
        defaultExtension = config.lastSaveExtension

        brushSize = config.brushSize
        updateBrushSize()
        view(R.id.stroke_width_bar) { t: MySeekBar ->
            t.progress = brushSize.toInt()
        }
        view(R.id.color_picker) { t: ImageView ->
            t.setOnClickListener { pickColor() }
        }
        view(R.id.undo) { t: ImageView ->
            t.setOnClickListener {
                view(R.id.my_canvas) { cc: MyCanvas ->
                    cc.undo()
                }
            }
        }
        view(R.id.eraser) { t: ImageView ->
            t.setOnClickListener {
                eraserClicked()
            }
            t.setOnClickListener {
                toast(R.string.eraser)
                true
            }
        }
        view(R.id.redo) { t: ImageView ->
            t.setOnClickListener {
                view(R.id.my_canvas) { cc: MyCanvas ->
                    cc.redo()
                }
            }
        }
        view(R.id.eye_dropper) { t: ImageView ->
            t.setOnClickListener {
                eyeDropperClicked()
            }
            t.setOnClickListener {
                toast(R.string.eyedropper)
                true
            }
        }

        checkIntents()
    }

    override fun onResume() {
        super.onResume()

        val isShowBrushSizeEnabled = config.showBrushSize
        view(R.id.stroke_width_bar) { t: MySeekBar ->
            t.beVisibleIf(isShowBrushSizeEnabled)
        }

        view(R.id.stroke_width_preview) { t: ImageView ->
            t.beVisibleIf(isShowBrushSizeEnabled)
        }

        view(R.id.my_canvas) { t: MyCanvas ->
            t.setAllowZooming(config.allowZoomingCanvas)
        }

        view(R.id.main_holder) { t: RelativeLayout ->
            updateTextColors(t)
        }

        view(R.id.stroke_width_bar) { t: MySeekBar ->
            if (isBlackAndWhiteTheme()) {
                t.setColors(0, config.canvasBackgroundColor.getContrastColor(), 0)
            }
        }

        if (config.preventPhoneFromSleeping) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }

        requestedOrientation =
            if (config.forcePortraitMode) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        invalidateOptionsMenu()
    }

    override fun onPause() {
        super.onPause()
        config.brushColor = color
        config.brushSize = brushSize
        if (config.preventPhoneFromSleeping) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        view(R.id.my_canvas) { t: MyCanvas ->
            t.mListener = null
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        menu.apply {
            findItem(R.id.menu_confirm).isVisible = isImageCaptureIntent || isEditIntent
            findItem(R.id.menu_save).isVisible = !isImageCaptureIntent && !isEditIntent
            findItem(R.id.menu_share).isVisible = !isImageCaptureIntent && !isEditIntent
            findItem(R.id.open_file).isVisible = !isEditIntent
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_confirm -> confirmImage()
            R.id.menu_save -> trySaveImage()
            R.id.menu_share -> shareImage()
            R.id.clear -> clearCanvas()
            R.id.open_file -> tryOpenFile()
            R.id.change_background -> changeBackgroundClicked()
            R.id.menu_print -> printImage()
            else -> return super.onOptionsItemSelected(item)
        }
        return true
    }

    override fun onBackPressed() {
        view(R.id.my_canvas) { t: MyCanvas ->
            val hasUnsavedChanges = savedPathsHash != t.getDrawingHashCode()
            if (hasUnsavedChanges && System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL) {
                lastSavePromptTS = System.currentTimeMillis()
                ConfirmationAdvancedDialog(
                    this,
                    "",
                    R.string.save_before_closing,
                    R.string.save,
                    R.string.discard
                ) {
                    if (it) {
                        trySaveImage()
                    } else {
                        super.onBackPressed()
                    }
                }
            } else {
                super.onBackPressed()
            }
        }
    }

    private fun launchSettings() {
        hideKeyboard()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
        super.onActivityResult(requestCode, resultCode, resultData)
        if (requestCode == PICK_IMAGE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
            tryOpenUri(resultData.data!!, resultData)
        } else if (requestCode == SAVE_IMAGE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
            val outputStream = contentResolver.openOutputStream(resultData.data!!)
            if (defaultExtension == SVG) {
                view(R.id.my_canvas) { t: MyCanvas ->
                    Svg.saveToOutputStream(this, outputStream, t)
                }
            } else {
                saveToOutputStream(outputStream, defaultExtension.getCompressionFormat(), false)
            }
            view(R.id.my_canvas) { t: MyCanvas ->
                savedPathsHash = t.getDrawingHashCode()
            }
        }
    }

    private fun tryOpenFile() {
        Intent(Intent.ACTION_GET_CONTENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "image/*"

            try {
                startActivityForResult(this, PICK_IMAGE_INTENT)
            } catch (e: ActivityNotFoundException) {
                toast(R.string.no_app_found)
            } catch (e: Exception) {
                showErrorToast(e)
            }
        }
    }

    private fun checkIntents() {
        if (intent?.action == Intent.ACTION_SEND && intent.type?.startsWith("image/") == true) {
            val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            tryOpenUri(uri!!, intent)
        }

        if (intent?.action == Intent.ACTION_SEND_MULTIPLE && intent.type?.startsWith("image/") == true) {
            val imageUris = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)!!
            imageUris.any { tryOpenUri(it, intent) }
        }

        if (intent?.action == Intent.ACTION_VIEW && intent.data != null) {
            tryOpenUri(intent.data!!, intent)
        }

        if (intent?.action == MediaStore.ACTION_IMAGE_CAPTURE) {
            val output = intent.extras?.get(MediaStore.EXTRA_OUTPUT)
            if (output != null && output is Uri) {
                isImageCaptureIntent = true
                intentUri = output
                defaultPath = output.path!!
                invalidateOptionsMenu()
            }
        }

        if (intent?.action == Intent.ACTION_EDIT) {
            val data = intent.data
            val output = intent.extras?.get(MediaStore.EXTRA_OUTPUT)
            if (data != null && output != null && output is Uri) {
                tryOpenUri(data, intent)
                isEditIntent = true
                intentUri = output
            }
        }
    }

    private fun getStoragePermission(callback: () -> Unit) {
        AutoPermissions.loadSelectedPermission(this,
            2048, Manifest.permission.WRITE_EXTERNAL_STORAGE, object : AutoPermissionsCallback {
                override fun onDenied(requestCode: Int, permissions: Array<String>) {
                    if (requestCode != 2048) {
                        toast(R.string.no_storage_permissions)
                        return
                    }
                    callback()
                }

                override fun onGranted(requestCode: Int, permissions: Array<String>) {

                }
            })
    }

    private fun tryOpenUri(uri: Uri, intent: Intent) = when {
        uri.scheme == "file" -> {
            uriToLoad = uri
            openPath(uri.path!!)
        }
        uri.scheme == "content" -> {
            uriToLoad = uri
            openUri(uri, intent)
        }
        else -> false
    }

    private fun openPath(path: String) = when {
        path.endsWith(".svg") -> {
            view(R.id.my_canvas) { t: MyCanvas ->
                t.mBackgroundBitmap = null
                Svg.loadSvg(this, File(path), t)
                defaultExtension = SVG
            }
            true
        }
        File(path).isImageSlow() -> {
            lastBitmapPath = path
            view(R.id.my_canvas) { t: MyCanvas ->
                t.drawBitmap(this, path)
            }
            defaultExtension = JPG
            true
        }
        else -> {
            toast(R.string.invalid_file_format)
            false
        }
    }

    private fun openUri(uri: Uri, intent: Intent): Boolean {
        val mime = MimeTypeMap.getSingleton()
        val type = mime.getExtensionFromMimeType(contentResolver.getType(uri)) ?: intent.type
        ?: contentResolver.getType(uri)
        return when (type) {
            "svg", "image/svg+xml" -> {
                view(R.id.my_canvas) { t: MyCanvas ->
                    t.mBackgroundBitmap = null
                    Svg.loadSvg(this, uri, t)
                }
                defaultExtension = SVG
                true
            }
            "jpg", "jpeg", "png", "gif", "image/jpg", "image/png", "image/gif" -> {
                view(R.id.my_canvas) { t: MyCanvas ->
                    t.drawBitmap(this, uri)
                }
                defaultExtension = JPG
                true
            }
            else -> {
                toast(R.string.invalid_file_format)
                false
            }
        }
    }

    private fun eraserClicked() {
        if (isEyeDropperOn) {
            eyeDropperClicked()
        }

        isEraserOn = !isEraserOn
        updateEraserState()
    }

    private fun updateEraserState() {
        val iconId = if (isEraserOn) {
            R.drawable.ic_eraser_off_vector
        } else {
            R.drawable.ic_eraser_on_vector
        }
        view(R.id.eraser) { t: ImageView ->
            t.setImageResource(iconId)
        }
        view(R.id.my_canvas) { t: MyCanvas ->
            t.toggleEraser(isEraserOn)
        }
    }

    private fun changeBackgroundClicked() {
        view(R.id.my_canvas) { t: MyCanvas ->
            val oldColor = (t.background as ColorDrawable).color
            ColorPickerDialog(this, oldColor) { wasPositivePressed, color ->
                if (wasPositivePressed) {
                    config.canvasBackgroundColor = color
                    setBackgroundColor(color)

                    if (uriToLoad != null) {
                        tryOpenUri(uriToLoad!!, intent)
                    }
                }
            }
        }
    }

    private fun eyeDropperClicked() {
        if (isEraserOn) {
            eraserClicked()
        }

        isEyeDropperOn = !isEyeDropperOn
        if (isEyeDropperOn) {
            eyeDropper.start()
        } else {
            eyeDropper.stop()
        }

        val iconId = if (isEyeDropperOn) {
            R.drawable.ic_colorize_off_vector
        } else {
            R.drawable.ic_colorize_on_vector
        }

        view(R.id.eye_dropper) { t: ImageView ->
            t.setImageResource(iconId)
        }
    }

    private fun confirmImage() {
        when {
            isEditIntent -> {
                try {
                    val outputStream = contentResolver.openOutputStream(intentUri!!)
                    saveToOutputStream(outputStream, defaultPath.getCompressionFormat(), true)
                } catch (e: Exception) {
                    showErrorToast(e)
                }
            }
            intentUri?.scheme == "content" -> {
                val outputStream = contentResolver.openOutputStream(intentUri!!)
                saveToOutputStream(outputStream, defaultPath.getCompressionFormat(), true)
            }
            else -> AutoPermissions.loadSelectedPermission(this,
                2048, Manifest.permission.WRITE_EXTERNAL_STORAGE, object : AutoPermissionsCallback {
                    override fun onDenied(requestCode: Int, permissions: Array<String>) {
                        if (requestCode != 2048) return
                        val fileDirItem =
                            FileDirItem(defaultPath, defaultPath.getFilenameFromPath())
                        getFileOutputStream(fileDirItem) {
                            saveToOutputStream(it, defaultPath.getCompressionFormat(), true)
                        }
                    }

                    override fun onGranted(requestCode: Int, permissions: Array<String>) {
                        TODO("Not yet implemented")
                    }

                })
        }
    }

    private fun saveToOutputStream(
        outputStream: OutputStream?,
        format: Bitmap.CompressFormat,
        finishAfterSaving: Boolean
    ) {
        if (outputStream == null) {
            toast(R.string.unknown_error_occurred)
            return
        }

        val quality = if (format == Bitmap.CompressFormat.PNG) {
            100
        } else {
            70
        }

        outputStream.use {
            view(R.id.my_canvas) { t: MyCanvas ->
                t.getBitmap().compress(format, quality, it)
            }
        }

        if (finishAfterSaving) {
            setResult(Activity.RESULT_OK)
            finish()
        }
    }

    private fun trySaveImage() {
        if (isQPlus()) {
            SaveImageDialog(
                this,
                defaultPath,
                defaultFilename,
                defaultExtension,
                true
            ) { fullPath, filename, extension ->
                val mimetype = if (extension == SVG) "svg+xml" else extension

                defaultFilename = filename
                defaultExtension = extension
                config.lastSaveExtension = extension

                Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                    type = "image/$mimetype"
                    putExtra(Intent.EXTRA_TITLE, "$filename.$extension")
                    addCategory(Intent.CATEGORY_OPENABLE)

                    try {
                        startActivityForResult(this, SAVE_IMAGE_INTENT)
                    } catch (e: ActivityNotFoundException) {
                        toast("R.string.system_service_disabled", Toast.LENGTH_LONG)
                    } catch (e: Exception) {
                        showErrorToast(e)
                    }
                }
            }
        } else {
            getStoragePermission {
                saveImage()
            }
        }
    }

    private fun saveImage() {
//        SaveImageDialog(this, defaultPath, defaultFilename, defaultExtension, false) { fullPath, filename, extension ->
//            savedPathsHash = binding.myCanvas.getDrawingHashCode()
//            saveFile(fullPath)
//            defaultPath = fullPath.getParentPath()
//            defaultFilename = filename
//            defaultExtension = extension
//            config.lastSaveFolder = defaultPath
//            config.lastSaveExtension = extension
//        }
    }

    private fun saveFile(path: String) {
        when (path.getFilenameExtension()) {
            SVG -> {
                view(R.id.my_canvas) { t: MyCanvas ->
                    Svg.saveSvg(this, path, t)
                }
            }
            else -> saveImageFile(path)
        }
        rescanPaths(arrayListOf(path)) {}
    }

    private fun saveImageFile(path: String) {
        val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
        getFileOutputStream(fileDirItem) {
            if (it != null) {
                writeToOutputStream(path, it)
                toast(R.string.file_saved)
            } else {
                toast(R.string.unknown_error_occurred)
            }
        }
    }

    private fun writeToOutputStream(path: String, out: OutputStream) {
        out.use {
            view(R.id.my_canvas) { t: MyCanvas ->
                t.getBitmap().compress(path.getCompressionFormat(), 70, out)
            }
        }
    }

    private fun shareImage() {
        view(R.id.my_canvas) { t: MyCanvas ->
            getImagePath(t.getBitmap()) {
                if (it != null) {
                    sharePathIntent(it, "com.atom.app.king")
                } else {
                    toast(R.string.unknown_error_occurred)
                }
            }
        }
    }

    private fun getImagePath(bitmap: Bitmap, callback: (path: String?) -> Unit) {
        val bytes = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, bytes)

        val folder = File(cacheDir, FOLDER_NAME)
        if (!folder.exists()) {
            if (!folder.mkdir()) {
                callback(null)
                return
            }
        }

        val newPath = "$folder/$FILE_NAME"
        val fileDirItem = FileDirItem(newPath, FILE_NAME)
        getFileOutputStream(fileDirItem) {
            if (it != null) {
                try {
                    it.write(bytes.toByteArray())
                    callback(newPath)
                } catch (e: Exception) {
                } finally {
                    it.close()
                }
            } else {
                callback("")
            }
        }
    }

    fun getFileOutputStream(
        fileDirItem: FileDirItem,
        callback: (outputStream: OutputStream?) -> Unit
    ) {
        val file = File(fileDirItem.path)
        if (file.parentFile?.exists() == false) {
            file.parentFile.mkdirs()
        }

        try {
            callback(FileOutputStream(file))
        } catch (e: Exception) {
            callback(null)
        }
    }

    private fun clearCanvas() {
        uriToLoad = null
        view(R.id.my_canvas) { t: MyCanvas ->
            t.clearCanvas()
        }
        defaultExtension = PNG
        defaultPath = ""
        lastBitmapPath = ""
    }

    private fun pickColor() {
        ColorPickerDialog(this, color) { wasPositivePressed, color ->
            if (wasPositivePressed) {
                if (isEyeDropperOn) {
                    eyeDropperClicked()
                }

                setColor(color)
            }
        }
    }

    fun setBackgroundColor(pickedColor: Int) {
        if (isEyeDropperOn) {
            eyeDropperClicked()
        }

        val contrastColor = pickedColor.getContrastColor()

        view(R.id.undo) { t: ImageView ->
            t.applyColorFilter(contrastColor)
        }

        view(R.id.eraser) { t: ImageView ->
            t.applyColorFilter(contrastColor)
        }

        view(R.id.redo) { t: ImageView ->
            t.applyColorFilter(contrastColor)
        }
        view(R.id.eye_dropper) { t: ImageView ->
            t.applyColorFilter(contrastColor)
        }

        if (isBlackAndWhiteTheme()) {
            view(R.id.stroke_width_bar) { t: MySeekBar ->
                t.setColors(0, contrastColor, 0)
            }
        }

        view(R.id.my_canvas) { t: MyCanvas ->
            t.updateBackgroundColor(pickedColor)
        }

        defaultExtension = PNG
        getBrushPreviewView().setStroke(getBrushStrokeSize(), contrastColor)
    }

    private fun setColor(pickedColor: Int) {
        color = pickedColor
        view(R.id.color_picker) { t: ImageView ->
            t.setFillWithStroke(color, config.canvasBackgroundColor, 0f)
        }

        view(R.id.my_canvas) { t: MyCanvas ->
            t.setColor(color)
        }
        isEraserOn = false
        updateEraserState()
        getBrushPreviewView().setColor(color)
    }

    private fun getBrushPreviewView() = viewReturn(R.id.stroke_width_preview) { t: ImageView ->
        t.background as GradientDrawable
    }

    private fun getBrushStrokeSize() =
        resources.getDimension(R.dimen.preview_dot_stroke_size).toInt()

    override fun toggleUndoVisibility(visible: Boolean) {
        view(R.id.undo) { t: ImageView ->
            t.beVisibleIf(visible)
        }
    }

    override fun toggleRedoVisibility(visible: Boolean) {
        view(R.id.redo) { t: ImageView ->
            t.beVisibleIf(visible)
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString(BITMAP_PATH, lastBitmapPath)

        if (uriToLoad != null) {
            outState.putString(URI_TO_LOAD, uriToLoad.toString())
        }
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        lastBitmapPath = savedInstanceState.getString(BITMAP_PATH)!!
        if (lastBitmapPath.isNotEmpty()) {
            openPath(lastBitmapPath)
        } else if (savedInstanceState.containsKey(URI_TO_LOAD)) {
            uriToLoad = Uri.parse(savedInstanceState.getString(URI_TO_LOAD))
            tryOpenUri(uriToLoad!!, intent)
        }
    }

    private var onStrokeWidthBarChangeListener: SeekBar.OnSeekBarChangeListener =
        object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                brushSize = progress.toFloat()
                updateBrushSize()
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        }

    private fun updateBrushSize() {
        view(R.id.my_canvas) { t: MyCanvas ->
            t.setBrushSize(brushSize)
        }
        val scale = Math.max(0.03f, brushSize / 100f)
        view(R.id.stroke_width_preview) { t: ImageView ->
            t.scaleX = scale
            t.scaleY = scale
        }
    }

    private fun printImage() {
        val printHelper = PrintHelper(this)
        printHelper.scaleMode = PrintHelper.SCALE_MODE_FIT
        try {

            view(R.id.my_canvas) { t: MyCanvas ->
                printHelper.printBitmap(getString(R.string.app_name), t.getBitmap())
            }

        } catch (e: Exception) {
            showErrorToast(e)
        }
    }

    private fun checkWhatsNewDialog() {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        AutoPermissions.parsePermissions(this, requestCode, permissions)
    }
}
